const os = require('os')

export function getNetworkInfos () {
  let networkInterfaces = os.networkInterfaces()
  let networkInfos = []
  for (let name in networkInterfaces) {
    let items = networkInterfaces[name]
    for (let i = 0; i < items.length; i++) {
      let item = items[i]
      if (item.address !== '127.0.0.1' && item.family === 'IPv4') {
        // 所以广播地址B与IP地址I，子网掩码M的关系为： B = (I & M)|~M;
        let broadcastAddress = ''
        for (let j = 0; j < 4; j++) {
          let I = Number(item.address.split('.')[j])
          let M = Number(item.netmask.split('.')[j])
          if (j) broadcastAddress += '.'
          broadcastAddress += (I & M) | (256 + (~M))
        }
        networkInfos.push({
          name: name,
          broadcastAddress,
          ...item
        })
      }
    }
  }
  return networkInfos
}

export function getNetworkInfo () {
  let networkInfos = getNetworkInfos()

  if (!networkInfos.length) return

  let selectMac = myStorage.getItem('selectMac', networkInfos[0].mac)
  if (selectMac) {
    return networkInfos.find(item => item.mac === selectMac)
  }
  return networkInfos[0]
}

export function getMineInfo () {
  let networkInfo = getNetworkInfo()
  let dnm = os.hostname()
  let xm = os.userInfo().username
  return {
    ...myStorage.getItem('mineInfo', {
      xm,
      tx: '',
      qm: ''
    }),
    mac: networkInfo.mac,
    dnm
  }
}

export function getTimeStr (time) {
  if (!time) return ''
  let data = new Date(time)
  // 现在
  let totime = new Date()
  // 今日0点
  let today0 = new Date(totime.getFullYear(), totime.getMonth(), totime.getDate())

  let deltaTime = time - today0.getTime()
  if (deltaTime > 0 && deltaTime < 24 * 60 * 60 * 1000) {
    // 今天
    return `${data.getHours()}:${data.getMinutes()}`
  } else if (time - today0 > -24 * 60 * 60 * 1000) {
    return '昨天'
  } else if (data.getFullYear() === totime.getFullYear()) {
    return `${totime.getMonth()}-${totime.getDate()}`
  } else {
    return `${totime.getFullYear()}-${totime.getMonth()}-${totime.getDate()}`
  }
}

export function getMsgText (msg = '') {
  if (!msg) return ''
  msg = msg.replace(/<img[^>]*>/ig, '[图片]')
    .replace(/<pre[^>]*>(.*)<\/pre>/gi, (w, r) => r)
    .replace(/\s/g, '&nbsp;')
  return msg
}

/*
<pre>     [./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 497 bytes {1}<br></pre>
 */

export function getPos (el, pEl) {
  let pos = {x: 0, y: 0}
  pos.height = el.offsetHeight
  pos.width = el.offsetWidth

  let $el = el
  do {
    if (el === pEl) break
    pos.x += el.offsetLeft
    pos.y += el.offsetTop
  } while ((el = el.offsetParent))

  el = $el
  do {
    if (el === pEl) break
    pos.x -= el.scrollLeft
    pos.y -= el.scrollTop
  } while ((el = el.parentElement))
  return pos
}

export function getPostion (el, pEl) {
  let pos = {}
  pos.x = el.offsetLeft
  pos.y = el.offsetTop
  while ((el = el.offsetParent)) {
    if (el === pEl) break
    pos.x += el.offsetLeft
    pos.y += el.offsetTop
  }
  pos.height = pEl ? pEl.offsetHeight : window.innerHeight
  pos.width = pEl ? pEl.offsetWidth : window.innerWidth
  return pos
}

export function insertHtml (html, el, win) {
  // 使编辑框获取焦点
  win = win || window || null
  if (!win) throw new Error('获取不到window')
  if (!win.getSelection) throw new Error('该浏览器不支持')

  el.focus()
  if (!win.getSelection) return ''
  // 获取selection
  let sel = win.getSelection()
  if (!(sel.getRangeAt && sel.rangeCount)) return ''
  // 获取选中内容的开始位置
  let range = sel.getRangeAt(0)
  // 删除选中的内容
  range.deleteContents()
  // 将传入的html转换为Node类型
  let div = document.createElement('div')
  div.innerHTML = html
  let node = div.firstChild
  let frag = document.createDocumentFragment()
  let lastNode = frag.appendChild(node)
  range.insertNode(frag)
  if (!lastNode) return ''
  range = range.cloneRange()
  range.setStartAfter(lastNode)
  range.collapse(true)
  sel.removeAllRanges()
  sel.addRange(range)
}

export function insertText (str, win) {
  win = win || window || null
  if (!win) throw new Error('获取不到window')
  if (!win.getSelection) throw new Error('该浏览器不支持')

  // 获取selection
  let selection = win.getSelection()
  // 获取选中内容的开始位置
  let range = selection.getRangeAt(0)
  // 删除选中的内容
  range.deleteContents()
  // 将传入的text转换为Node类型
  let span = document.createElement('span')
  span.innerText = str
  let frag = document.createDocumentFragment()
  let lastNode = frag.appendChild(span)
  range.insertNode(frag)
  if (!lastNode) return ''
  range = range.cloneRange()
  range.setStartAfter(lastNode)
  range.collapse(true)
  selection.removeAllRanges()
  selection.addRange(range)
}

export default {
  getPos,
  getPostion,
  insertHtml,
  insertText,
  getTimeStr,
  getMsgText,
  getMineInfo,
  getNetworkInfo,
  getNetworkInfos
}
